package utils

import (
	"bytes"
	"crypto/rand"
	"encoding/base64"
	"encoding/gob"
	"fmt"
	"reflect"
)

func GetRandomString(n int) string {
	// 数据池
	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	var bytes = make([]byte, n)
	// 获取随机字符串
	rand.Read(bytes)
	for i, b := range bytes {
		// 将随机字符串%数据池长度，取余，然后将这个值当做下标获取数据池中数据
		bytes[i] = alphanum[b%byte(len(alphanum))]
	}
	return string(bytes)
}

func EnGob(data string) bytes.Buffer {
	var buffer bytes.Buffer
	enc := gob.NewEncoder(&buffer) // 获取编码器
	enc.Encode(&data)              //编码
	return buffer
}

func DeGob(data bytes.Buffer) bytes.Buffer {
	var buffer bytes.Buffer
	dec := gob.NewDecoder(bytes.NewReader(buffer.Bytes()))
	dec.Decode(&data)
	return data
}

func EnBase64(data string) string {
	return base64.StdEncoding.EncodeToString([]byte(data))
}

func DeBase64(data string) string {
	byte, _ := base64.StdEncoding.DecodeString(data)
	return string(byte)
}

func ToInt64(value interface{}) (d int64, err error) {
	val := reflect.ValueOf(value)
	switch value.(type) {
	case int, int8, int16, int32, int64:
		d = val.Int()
	case uint, uint8, uint16, uint32, uint64:
		d = int64(val.Uint())
	default:
		err = fmt.Errorf("ToInt64 need numeric not `%T`", value)
	}
	return
}
